package com.jvm;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.InvocationTargetException;

public class JVM_09_自定义类加载器 extends ClassLoader {

    @Override
    protected Class<?> findClass(String moduleName, String name) {
        // 自定义加载器直接从磁盘中加载指定的 class 文件
        File file = new File("Hello.class");
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int b = 0;
            while ((b = fileInputStream.read()) != 0) {
                byteArrayOutputStream.write(b);
            }
            byte[] bytes = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            fileInputStream.close();
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(moduleName, name);
    }

    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, NoSuchMethodException, SecurityException {
        ClassLoader classLoader = new JVM_09_自定义类加载器();
        // 按照类加载器的过程逐级向上查找是否加载了当前类的对象 因为都没有加载过， 又制定了自定义的 ClassLoader,所以要让自定义加载器自己加载
        Class<?> class1 = classLoader.loadClass("Hello");
        Hello hello = (Hello) class1.getDeclaredConstructor().newInstance();
        hello.hello();
        System.err.println(classLoader.getClass().getClassLoader());
        System.err.println(classLoader.getParent());
    }
}
